package com.example.blogapi;

import com.example.blogapi.controller.BlogController;
import com.example.blogapi.controller.CategoryController;
import com.example.blogapi.controller.TagController;
import com.example.blogapi.controller.UserController;
import com.example.blogapi.dao.DatabaseManager;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class Server {
    private final int port;
    private HttpServer server;

    public Server(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        // 初始化数据库
        DatabaseManager.initDatabase();

        // 创建HTTP服务器
        server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
        
        // 设置线程池
        server.setExecutor(Executors.newFixedThreadPool(10));
        
        // 注册路由
        server.createContext("/api/users", new UserController());
        server.createContext("/api/categories", new CategoryController());
        server.createContext("/api/tags", new TagController());
        server.createContext("/api/blogs", new BlogController());
        
        // 启动服务器
        server.start();
        
        System.out.println("Server started on port " + port);
    }

    public void stop() {
        if (server != null) {
            server.stop(0);
            System.out.println("Server stopped");
        }
        
        // 关闭数据库连接
        DatabaseManager.closeConnection();
    }
}